<template>
  <ul class="article-list box-border">
    <li v-for="item in articleData.list" :key="item._id">
      <div class="flex items-center">
        <p
          class="text-lg font-semibold article-title cursor-pointer flex-1"
          @click="toDetail(item._id)"
        >
          {{ item.title }}
        </p>
        <el-dropdown @command="handleCommand" v-if="showMoreOperation">
          <el-icon size="16" color="#000"><More /></el-icon>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :command="`edit-${item._id}`">编辑</el-dropdown-item>
              <el-dropdown-item :command="`delete-${item._id}`">删除</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="flex">
        <img
          class="article-img cursor-pointer"
          :src="item?.image?.url || coverImg"
          alt=""
          @click="toDetail(item._id)"
        />
        <div class="ml-4 flex-1 cursor-pointer article-excerpt" @click="toDetail(item._id)">
          {{ item.excerpt }}
        </div>
      </div>
    </li>
  </ul>
  <div
    v-if="loading"
    v-loading="loading"
    element-loading-background="#f6f6f6"
    class="my-5 h-5"
  ></div>
</template>

<script lang="ts">
import {
  defineComponent,
  reactive,
  onMounted,
  onBeforeUnmount,
  computed,
  ref,
  watch,
  nextTick,
} from 'vue'
import {
  getArticlesByColumnId,
  ArticleDto,
  deleteArticle,
} from '@/services/ApiServer/ArticleRequest'
import { useRoute, useRouter } from 'vue-router'
import { More } from '@element-plus/icons-vue'
import {
  ElIcon,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElMessageBox,
  ElMessage,
} from 'element-plus'
import { useUserStore } from '@/store/user'

export default defineComponent({
  name: 'columnList',
  components: {
    More,
    ElIcon,
    ElDropdown,
    ElDropdownMenu,
    ElDropdownItem,
  },
  setup() {
    let articleData = reactive({
      list: [] as ArticleDto[],
      pageNo: 0,
      pageSize: 8,
      total: 0,
    })
    const route = useRoute()
    const router = useRouter()
    const columnId = computed(() => {
      return route.params.columnId as string
    })
    const userStore = useUserStore()
    const showMoreOperation = computed(() => {
      return userStore.userInfo?.column === columnId.value
    })
    const coverImg = ref(new URL('../../assets/images/noData.webp', import.meta.url).href)
    let loading = ref(false)
    const getArticleList = async () => {
      if (
        (articleData.total > articleData.pageNo * articleData.pageSize ||
          articleData.pageNo === 0) &&
        !loading.value
      ) {
        articleData.pageNo += 1
        loading.value = true
        const res = await getArticlesByColumnId(columnId.value, {
          pageSize: articleData.pageSize,
          currentPage: articleData.pageNo,
        })
        if (res && res.code === 0 && res.data) {
          articleData.list = articleData.list.concat(res.data.list)
          articleData.total = res.data.count
        }
        nextTick(() => {
          loading.value = false
        })
      }
    }
    const toDetail = (id: string) => {
      router.push(`/column/detail/${columnId.value}/${id}`)
    }
    const scrollChange = () => {
      const htmlTag = document.getElementsByTagName('html')[0]
      const { scrollTop, scrollHeight, clientHeight } = htmlTag
      if (scrollHeight - 120 < scrollTop + clientHeight) {
        getArticleList()
      }
    }
    const reset = () => {
      articleData.list = []
      articleData.pageNo = 0
      getArticleList()
      document.getElementsByTagName('html')[0].scrollTop = 0
    }
    const handleCommand = (command: string) => {
      const id = command.split('-')[1]
      if (command.indexOf('delete') > -1) {
        ElMessageBox.confirm('确认是否删除该篇文章?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(async () => {
          const res = await deleteArticle(id)
          if (res && res.code === 0) {
            ElMessage.success('删除成功！')
            reset()
          }
        })
      } else {
        router.push(`/writeArticle?id=${id}`)
      }
    }
    watch(columnId, (val) => {
      if (val) {
        reset()
      }
    })
    onMounted(() => {
      getArticleList()
      window.addEventListener('scroll', scrollChange)
    })
    onBeforeUnmount(() => {
      window.removeEventListener('scroll', scrollChange)
    })
    return {
      articleData,
      toDetail,
      coverImg,
      handleCommand,
      showMoreOperation,
      loading,
    }
  },
})
</script>

<style lang="scss" scoped>
.article-list {
  width: 700px;
  margin: 10px auto;
  background: #fff;
  border-radius: 2px;
  box-shadow: 0 1px 3px hsl(0deg 0% 7% / 10%);
  li {
    border-bottom: 1px solid rgb(246, 246, 246);
    padding: 16px 20px;
    .article-title {
      &:hover {
        color: #175199;
      }
    }
    .article-img {
      width: 190px;
      height: 120px;
    }
    .article-excerpt {
      &:hover {
        color: #646464;
      }
    }
  }
}
</style>
